//
//  UIImage+HBCategory.m
//  HBLibary
//
//  Created by Rambo on 2018/10/26.
//

#import "UIImage+HBCategory.h"
#import <objc/runtime.h>
#import <Photos/Photos.h>

@implementation UIImage (HBCategory)

/**
 layer转换成Image
 
 @param layer layer
 @return image
 */
+ (UIImage *)hb_imageWithLayer:(CALayer*)layer{
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, NO, [UIScreen mainScreen].scale);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    [layer renderInContext:contextRef];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


/**
 设置图片透明度
 
 @param alpha 透明度
 @param image 图片
 @return 新图片
 */
+ (UIImage *)hb_imageByApplyingAlpha:(CGFloat)alpha image:(UIImage*)image{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);
    
    CGContextScaleCTM(ctx, 1, -1);
    
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    
    CGContextSetAlpha(ctx, alpha);
    
    CGContextDrawImage(ctx, area, image.CGImage);
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

/**
 标识符
 */
- (void)setIdentifier:(NSString *)identifier{
    objc_setAssociatedObject(self, @selector(identifier), identifier, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)identifier{
    return objc_getAssociatedObject(self, @selector(identifier));
}

+ (UIImage*)hb_carveImageCenterWithImage:(UIImage*)image{
    
    CGFloat screenScale = [UIScreen mainScreen].scale;
    
    CGFloat size = MIN(image.size.width/screenScale, image.size.height/screenScale);
    
    CGFloat x = (image.size.width/screenScale - size ) * 0.5;
    CGFloat y = (image.size.height/screenScale - size ) * 0.5;
    
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(x*screenScale, y * screenScale, size * screenScale, size * screenScale));
    
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    
    return newImage;
}


+ (UIImage *)hb_convertToCircleWithImage:(UIImage *)rectangleImage onWidth:(CGFloat)width onColor:(UIColor *)color
{
    
    CGFloat size = MIN(rectangleImage.size.width, rectangleImage.size.height );
    CGFloat imageWidth = size + 2 * width;
    CGFloat imageHeight = size + 2 * width;
    
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageWidth, imageHeight), NO, [UIScreen mainScreen].scale);
    
    UIGraphicsGetCurrentContext();
    
    CGFloat radius  = size * 0.5;
    
    UIBezierPath *bezierPath = [UIBezierPath
                                bezierPathWithArcCenter:CGPointMake(imageWidth * 0.5, imageHeight * 0.5)
                                radius:radius startAngle:0 endAngle:M_PI * 2 clockwise:YES];
    
    bezierPath.lineWidth = width;
    [color setStroke];
    [bezierPath stroke];
    [bezierPath addClip];
    
    [rectangleImage drawInRect:CGRectMake(width, width, rectangleImage.size.width, rectangleImage.size.height)];
    
    UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return circleImage;
}

+ (UIImage *)hb_carveRoundedCornersWithImage:(UIImage*)image{
    UIImage *newImage = [self hb_carveImageCenterWithImage:image];
    
    
    UIGraphicsBeginImageContextWithOptions(newImage.size, NO, [UIScreen mainScreen].scale);
    
    UIGraphicsGetCurrentContext();
    
    CGFloat radius  = newImage.size.width * 0.5;
    
    CGRect rect = CGRectMake(0, 0, newImage.size.width, newImage.size.height);
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];

//    [bezierPath stroke];
    [bezierPath addClip];
    
    [newImage drawInRect:rect];
    
    UIImage *circleImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return circleImage;
}

/**
 保存图片
 
 @param image 图片
 @param saveHandle 保存回调
 @param statusHandle 相册权限回调，没有权限的时才有回调
 */
+ (void)hb_saveImage:(UIImage*)image saveHandle:(void(^)(BOOL success, NSError * _Nullable error))saveHandle statusHandle:(void(^)(void))statusHandle{
    if (image == nil) return;
    //    Privacy - Photo Library Usage Description
    //    Privacy - Photo Library Additions Usage Description
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusNotDetermined || status == PHAuthorizationStatusAuthorized) {
            //保存到相册
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    !saveHandle ? : saveHandle(success, error);
                });
                
            }];
        }
        
        else{
            dispatch_async(dispatch_get_main_queue(), ^{
                !statusHandle ? : statusHandle();
            });
        }
    }];
}

/**
 压缩图片
 
 @param KByte KByte
 */
- (NSData*)hb_compressKByte:(NSInteger)KByte{
    CGSize imageSize = self.size;
    NSData *data = UIImageJPEGRepresentation(self, 1);
    if (data.length / 1024.0f < KByte || KByte <= 0 || imageSize.width <= 0.0f || imageSize.height <= 0.0f) {
        return data;
    }
    
    CGFloat max = 1;
    CGFloat min = 0;
    while (ceilf(data.length / 1024.0f) > KByte || ceilf(data.length / 1024.0f) < KByte) {
        CGFloat result = (max + min) * 0.5;
        if ([[NSString stringWithFormat:@"%.4f",max] isEqualToString:[NSString stringWithFormat:@"%.4f",min]]) {
            break;
        }
        CGSize newSize = CGSizeMake(imageSize.width*result, imageSize.height*result);
        
        UIGraphicsBeginImageContext(newSize);
        [self drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(newImage, 1);
//        NSLog(@"%f",ceilf(data.length / 1024.0f));
        if (ceilf(data.length / 1024.0f) > KByte) {
            max = result;
        }else if (ceilf(data.length / 1024.0f) < KByte){
            min = result;
        }
    }
//    NSLog(@"%f",data.length / 1024.0f);
    return data;
}

@end
